package com.xunyin.nettyV.client;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author xunyinyunshang  <3594419785@qq.com>
 * @date 2023-3-16
 * mqtt客户端发布消息
 */
@Slf4j
public class PubMsg {

    /**
     * 功能描述:连接MQ
     *
     * @param clientId
     * @param userName
     * @param password
     * @author zhangpu
     * @date 2022/4/2
     */
    private static MqttClient connect(String clientId, String userName, String password) throws MqttException {
        MemoryPersistence persistence = new MemoryPersistence();
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(false);
        //connOpts.setUserName(userName);
        //connOpts.setPassword(password.toCharArray());
        connOpts.setConnectionTimeout(10);// 设置超时时间
        connOpts.setKeepAliveInterval(20); // 设置会话心跳时间
        // broker，clientid即连接MQTT的客户端ID，一般以唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
        MqttClient mqttClient = new MqttClient(MqConfig.broker, clientId, persistence);
        mqttClient.setCallback(new PushCallback("test"));//设置回调
        mqttClient.connect(connOpts);
        return mqttClient;
    }

    /**
     * 功能描述:发送消息
     *
     * @param msg
     * @param clientId
     * @param topic
     * @author zhangpu
     * @date 2022/4/2
     */
    public static void publish(String msg, String clientId, String topic) throws MqttException {
        MqttClient mqttClient = connect(clientId, MqConfig.userName, MqConfig.passWord);
        if (mqttClient != null) {
            MqttMessage message = new MqttMessage(msg.getBytes());
            message.setQos(MqConfig.qos);
            //重新连接MQTT服务时，不需要接收该主题最新消息，设置retained为false
            //重新连接MQTT服务时，需要接收该主题最新消息，设置retained为true;
            message.setRetained(false);
            System.out.println("连接mqtt成功，发送消息=" + JSONObject.toJSONString(message));
            mqttClient.publish(topic, message);
        } else {
            System.out.println("连接mqtt失败");
        }
        if (mqttClient != null) {
            mqttClient.disconnect();//释放连接
        }
    }


    /**
     * 给指定设备发送指令
     *
     * @param mac
     * @param commandType
     * @param switchFlag
     * @param voiceText
     * @param type 0表示不支持分控,1表示支持分控
     * @param relayList
     * //subPort 0表示固定电源开关
     */
    public static void sendCommand(String mac, Integer commandType,
                                   Integer switchFlag, String voiceText,
                                   Integer type,List relayList,String serverIp) throws MqttException {

        JSONObject reBasicDown = new JSONObject();
        reBasicDown.put("mac", mac);

        // 不支持分控情况下,电源开关  relay 0 关   1 开
        // 支持分控情况下, 端口（subPort）0表示固定电源开关，1,2,3端口随机配置灯光、空调、麻将机、桌球锁球器
        if (commandType == 1) {

            // 不支持分控,传标识
            if(type == 0){

                reBasicDown.put("relay", switchFlag);

            // 支持分控，传标识数组
            }else if(type == 1){

/*                List relayList = new ArrayList<>();
                relayList.add(0);
                relayList.add(0);
                relayList.add(0);
                relayList.add(0);
                for(int i=0;i<relayList.size();i++){
                    if(i == subPort){
                        relayList.set(subPort,switchFlag);
                    }
                }*/

                reBasicDown.put("relay",relayList.toArray());
            }

        // 门锁开关 doorSwitch  0 关  1  开
        } else if (commandType == 2) {
            reBasicDown.put("doorSwitch", switchFlag);
        // 发送语音播报
        } else if (commandType == 3) {
            reBasicDown.put("voice", voiceText);
        // 设备重启
        } else if (commandType == 4) {
            reBasicDown.put("reboot", switchFlag);
        // 修改连接的服务器Ip
        }else if (commandType == 5) {
            reBasicDown.put("ip", serverIp);
        }

        String randFlag = RandomUtil.randomNumbers(5);
        publish(reBasicDown.toJSONString(), "client-id-" + mac + "" + randFlag, "/hxx/qpzz/dev/" + mac + "/basic/down");
    }

/*  /hxx/qpzz/dev/80646F0F380C/basic/down

    // doorSwitch  门锁开关   0 关  1  开
    {"mac":"80646F0F380C","doorSwitch":1}

    // relay  电源开关   0 关   1 开
    {"mac":"80646F0F380C","relay":0}

    // 重启设备
    {"mac":"80646F0F380C","reboot":1}

    //发送语音
    {"mac":"80646F0F380C","voice":"订单将在15分钟后到期！可通过小程序续单"}*/


    public static void main(String[] args) throws MqttException {
        //publish("message content", "client-id-0", "test-topic");
        String mac = "80646F0F380C";
        JSONObject reBasicDown = new JSONObject();
        reBasicDown.put("mac", "80646F0F380C");
        //reBasicDown.put("voice","语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音语音");
        //reBasicDown.put("time", DateUtils.parseDate2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
        //reBasicDown.put("reboot",0);
        //reBasicDown.put("ip", MqConfig.ip);
        //reBasicDown.put("port", MqConfig.port);
        //publish(reBasicDown.toJSONString(), "client-id-" + mac, "/hxx/qpzz/dev/" + mac + "/basic/down");

        int subPort =0;

        List relayList = new ArrayList<>();
        relayList.add(0);
        relayList.add(0);
        relayList.add(0);
        relayList.add(0);
        for(int i=0;i<relayList.size();i++){
            if(i == subPort){
                relayList.set(subPort,1);
            }
        }

        System.out.println(relayList.toArray());

    }

}
